﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using CalcSharp.Core.Controlls;
using CalcSharp.Core.IO;
using CalcSharp.MDIUI;
using CalcSharp.MDIUI.ToolBars;
using CalcSharp.Properties;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;
using WeifenLuo.WinFormsUI.Docking;

namespace CalcSharp
{

    public partial class Parentform : GlassForm
    {
        private int frontindex;
        private int last_formc;
        private SimpleInput CsSimple;
        private about aboutfrm;
        private MemMap MemoryMap;
        private FileExplorer FileExplorer;

        #region Win7 compatibility
        private TaskbarManager WindowsTaskbar;
        private bool Win7;
        #endregion

        public Parentform()
        {
            InitializeComponent();
            try
            {
                this.WindowsTaskbar = TaskbarManager.Instance;
                this.WindowsTaskbar.ApplicationId = "Calc#";
            }
            catch (PlatformNotSupportedException) { Win7 = false; }
            this.frontindex = -1;
        }

        private void Parentform_AeroGlassCompositionChanged(object sender, AeroGlassCompositionChangedEvenArgs e)
        {
            if (e.GlassAvailable)
            {
                this.statusbar.Renderer = new NonClientAreaRenderer();
                this.MainMenuStrip.Renderer = new NonClientAreaRenderer();
                this.OpacityCtrl.BackColor = Color.Black;
                ExcludeControlFromAeroGlass(dockPanel1);
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private delegate void AnimateCalllback(bool animate);

        public void AnimateProgress(bool animate)
        {
            if (this.InvokeRequired) this.Invoke(new AnimateCalllback(AnimateProgress), new object[] { animate });
            else
            {
                if (animate)
                {
                    this.ProgressIndicator.Style = ProgressBarStyle.Marquee;
                    if (Win7) WindowsTaskbar.SetProgressState(TaskbarProgressBarState.Indeterminate, this.Handle);
                }
                else
                {
                    if (Win7) WindowsTaskbar.SetProgressState(TaskbarProgressBarState.NoProgress, this.Handle);
                    this.ProgressIndicator.Style = ProgressBarStyle.Blocks;
                }
                
            }
        }

        public void UpdateProgressTime(TimeSpan t)
        {
            StringBuilder text = new StringBuilder();
            text.Append("Last operation completed in: ");
            if (t.TotalHours > 1)
            {
                text.Append(Math.Round(t.TotalHours, 4));
                text.Append(" hours");
            }
            else if (t.TotalMinutes > 1)
            {
                text.Append(Math.Round(t.TotalMinutes, 4));
                text.Append(" minutes");
            }
            else
            {
                text.Append(Math.Round(t.TotalSeconds, 4));
                text.Append(" seconds");
            }
            this.Statustext.Text = text.ToString();
        }

        public void LoadSettings()
        {
            string img = (string)Settings.Default["ParentBackgoundImage"];
            this.DoubleBuffered = (bool)Settings.Default["DoubleBuffer"];
            this.OpacityCtrl.Value =  (int)CalcSharp.Properties.Settings.Default["OpacityValue"];
            this.OpacityCtrl_Scroll(this, null);
            foreach (Control control in this.Controls)
            {
                if (control is MdiClient) // located it
                {
                    if (!string.IsNullOrEmpty(img)) control.BackgroundImage = Image.FromFile(img);
                    else control.BackgroundImage = Properties.Resources.Background;
                    control.BackgroundImageLayout = (ImageLayout)Settings.Default["ParentBackgroundMode"];
                    break;
                }
            }
        }

        private void Parentform_Load(object sender, EventArgs e)
        {
            this.LoadSettings();


            this.MemoryMap = new MemMap();
            this.FileExplorer = new FileExplorer();
            this.MemoryMap.Show(dockPanel1);
            this.FileExplorer.Show(dockPanel1);
            this.MemoryMap.DockState = DockState.DockRightAutoHide;
            this.FileExplorer.DockState = DockState.DockRightAutoHide;

            Program.ConsoleForm.MdiParent = this;
            Program.ConsoleForm.Show();
            Parentform_Resize(sender, e);
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (this.last_formc != this.MdiChildren.Length) this.redrawstatusbar();
            timeMenu.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString();
            dateMenu.Text = timeMenu.ToolTipText = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + " - " + DateTime.Now.DayOfWeek.ToString();
        }

        public void redrawstatusbar()
        {
            if (this.last_formc != this.MdiChildren.Length)
            {
                int i;
                ImageList icons = new ImageList();
                WindowToolbar.Items.Clear();
                statusbar.ImageList = icons;
                icons.Images.Clear();
                for (i = 0; i < this.MdiChildren.Length; i++)
                {
                    ToolStripButton n = new ToolStripButton();
                    n.DisplayStyle = ToolStripItemDisplayStyle.Image;
                    n.Name = this.MdiChildren[i].Name;
                    n.ToolTipText = this.MdiChildren[i].Text;
                    n.Text = this.MdiChildren[i].Text;
                    n.Click += new EventHandler(n_Click);
                    n.Image = this.MdiChildren[i].Icon.ToBitmap();
                    WindowToolbar.Items.Add(n);
                }
                last_formc = this.MdiChildren.Length;
            }
        }

        private void Parentform_MdiChildActivate(object sender, EventArgs e)
        {
            redrawstatusbar();
        }

        void n_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripButton)
            {
                int i;
                for (i = 0; i < this.MdiChildren.Length; i++)
                {
                    if (this.MdiChildren[i].Name == ((ToolStripButton)sender).Name)
                    {
                        if (i == this.frontindex)
                        {
                            if (MdiChildren[i].WindowState == FormWindowState.Minimized) MdiChildren[i].WindowState = FormWindowState.Normal;
                            else MdiChildren[i].WindowState = FormWindowState.Minimized;
                        }
                        else
                        {
                            MdiChildren[i].Show();
                            MdiChildren[i].BringToFront();
                            if (MdiChildren[i].WindowState == FormWindowState.Minimized) MdiChildren[i].WindowState = FormWindowState.Normal;
                            this.frontindex = i;
                        }
                        break;
                    }
                }
            }
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            settings_editor s = new settings_editor();
            s.MdiParent = this;
            s.Show();
        }

        private void manualPagesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.man = new HelpDisplay();
            Program.man.MdiParent = this;
            Program.man.Show();
        }

        private void Parentform_FormClosing(object sender, FormClosingEventArgs e)
        {
            switch (Settings.Default.MemAutoSaveType)
            {
                case 1:
                    DialogResult Dr = MessageBox.Show("Save Calculator memory state", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (Dr == DialogResult.Yes)
                        Program.loaded.SerializeMem(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat");
                    else if (File.Exists(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat"))
                         File.Delete(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat");
                    break;
                case 2:
                    Program.loaded.SerializeMem(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat");
                    break;
                default:
                    if (File.Exists(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat"))
                        File.Delete(FileHelper.ProfileDir + @"\CalcSharpUserData\resrume.dat");
                    break;
            }
            CalcSharp.Properties.Settings.Default.Save();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.aboutfrm = new about();
            this.aboutfrm.MdiParent = this;
            this.aboutfrm.Show();
        }

        private void databaseImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void easyCalcToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CsSimple = new SimpleInput();
            CsSimple.MdiParent = this;
            CsSimple.Show();
        }

        private void saveCalculatorMemoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadSaveMemDlg.Description = "Select folder where you want to save the calculator's memory";
            LoadSaveMemDlg.ShowNewFolderButton = true;
            if (LoadSaveMemDlg.ShowDialog() == DialogResult.OK)
            {
                Program.loaded.SerializeMem(LoadSaveMemDlg.SelectedPath);
            }
        }

        private void loadCalculatorMemoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadSaveMemDlg.Description = "Select folder which contains a calculator memory save";
            LoadSaveMemDlg.ShowNewFolderButton = false;
            if (LoadSaveMemDlg.ShowDialog() == DialogResult.OK)
            {
                Program.loaded.DeSerializeMem(LoadSaveMemDlg.SelectedPath);
            }
        }

        public void UpdateMemoryMap(mMapSegment segment)
        {
            if (this.MemoryMap != null) this.MemoryMap.UpdateMemMap(segment);
        }

        private void OpacityCtrl_Scroll(object sender, EventArgs e)
        {
            this.Opacity = (double)this.OpacityCtrl.Value / 100;
            this.OpacityValue.Text = this.OpacityCtrl.Value.ToString() + "%";
            CalcSharp.Properties.Settings.Default["OpacityValue"] = this.OpacityCtrl.Value;
        }

        private void restartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void WinCascade_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void WinTileVertical_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void WinTileHorizontal_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void WinMinimizeAll_Click(object sender, EventArgs e)
        {
            if (WinMinimizeAll.Text == "Minimize All")
            {
                foreach (Form childForm in MdiChildren)
                {
                    childForm.WindowState = FormWindowState.Minimized;
                }
                WinMinimizeAll.Text = "Restore All";
            }
            else
            {
                foreach (Form childForm in MdiChildren)
                {
                    childForm.WindowState = FormWindowState.Normal;
                }
                WinMinimizeAll.Text = "Minimize All";
            }
        }

        private void WinCloseAll_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                if (childForm.Name != Program.ConsoleForm.Name) childForm.Close();
            }
        }

        private void Parentform_Resize(object sender, EventArgs e)
        {
            int sumwidth = 0;
            foreach (ToolStripItem c in this.statusbar.Items)
            {
                if (c.Name != "Statustext") sumwidth += c.Width;
            }
            this.Statustext.Width = this.statusbar.Width - sumwidth - 30;
        }
    }
}
